<template>
	<view class="tn-p">

		<view v-if="!data.order_no">
			<view class="flex-center tn-gray_text">加载中...</view>
		</view>

		<view class="ta-card" v-if="data.order_no">
			<view class="ta-card-body">
				<view class="flex-x flex-align-center" v-if="data.delivery_type" @click="doSelectAddress">
					<uv-icon size="60rpx" color="rgba(0,0,0,0.3)" name="map" />
					<view class="flex-1 tn-pl-xs" v-if="data.address">
						<view class="flex-x flex-x-between flex-align-center">
							<view class="flex-x tn-text-bold">
								<text>{{ data.address.user_name }}</text>
								<text class="tn-ml-sm">{{ data.address.user_phone }}</text>
							</view>
							<view class="ta-desc-text">
								{{ data.address.region_prov }} {{ data.address.region_city }} {{ data.address.region_area }}
							</view>
						</view>
						<view class="tn-mt-xs ta-desc-text">{{ data.address.region_addr }}</view>
					</view>
					<view class="flex-1 tn-pl flex-align-center" v-else>
						<view class="ta-desc-text">未设置收货地址！</view>
					</view>
				</view>
				<view v-else class="tn-text-center">
					<text class="ta-desc-text tn-text-sm">虚拟产品，无需发货！</text>
				</view>
			</view>
		</view>

		<view v-if="data.order_no" class="ta-card">
			<view class="ta-card-head">
				<text>{{ data.store.name }}</text>
			</view>
			<view class="ta-card-head">
				<text>{{ data.order_no }}</text>
				<view>
					<!-- 订单流程状态(0已取消,1预订单,2待支付,3待审核,4待发货,5已发货,6已收货,7已评论) -->
					<text v-if="data.status == 0" class="ta-main-text">已取消</text>
					<text v-if="data.status == 1" class="ta-main-text">预订单</text>
					<text v-if="data.status == 2" class="ta-main-text" @click="goto.payment(code)">待支付</text>
					<text v-if="data.status == 3" class="ta-main-text" @click="goto.payment(code)">待审核</text>
					<text v-if="data.status == 4" class="ta-main-text">待发货</text>
					<text v-if="data.status == 5" class="ta-main-text">待收货</text>
					<text v-if="data.status == 6" class="ta-main-text">待评论</text>
					<text v-if="data.status == 7" class="ta-main-text">已完成</text>
				</view>
			</view>
			<view v-if="data.items" class="ta-card-body">
				<view class="flex-x tn-pt-xs tn-pb-xs" v-for="xx in data.items" :key="xx.unid"
					@click="goto.goods(xx.gcode, xx.ghash)">
					<uv-image :src="xx.gcover" height="90rpx" width="90rpx" radius="10rpx" :lazy-load="true" />
					<view class="flex-1 flex-y flex-y-center tn-pl-sm" style="justify-content:space-evenly;">
						<text class="ta-main-text uv-line-1 tn-text-bold ">{{ xx.gname }}</text>
						<text class="ta-desc-text uv-line-1 tn-text-sm">{{ showSpec(xx.gspec) }}</text>
					</view>
					<view class="tn-text-right flex-align-center">
						<view class="flex-y">
							<view class="tn-text-bold" v-if="Number(xx.price_selling) > 0">
								<uv-text mode="price" type='error' :text="xx.price_selling" />
							</view>
							<view class="tn-text-bold ta-desc-text" v-if="Number(xx.price_selling) <= 0">免费</view>
							<view class="ta-desc-text tn-text-xs"> x {{ xx.stock_sales }} {{ xx.gunit }}</view>
						</view>
					</view>
				</view>
			</view>
			<view class="ta-card-foot flex-wrap flex-x-between">
				<view class="flex-x flex-1 flex-x-normal flex-wrap">
					<view>共包含 <text class="tn-text-bold tn-red_text">{{ stocks }}</text> 件商品</view>
					<view>
						<text class="tn-pr-xs">，累计</text>
						<text class="tn-text-bold tn-red_text">
							{{ Number(data.amount_goods) + Number(data.amount_express) }}
						</text>
						<text class="tn-pl-xs">元</text>
					</view>
					<view class="tn-pl-xs nowrap" v-if="Number(data.amount_express) > 0">
						( 含运费 {{ Number(data.amount_express) }} 元 )
					</view>
					<view v-if="Number(data.amount_reduct) > 0">
						，减免 <text class="tn-text-bold tn-red_text">{{ Number(data.amount_reduct) }}</text> 元。
					</view>
				</view>
			</view>
			<view class="ta-card-foot flex-wrap flex-x-between ">
				<view class="tn-text-xs ta-desc-text flex-center">{{ data.create_time }}</view>
				<view class="ta-main-text flex-center" style="justify-content: end;">
					<text class="ta-desc-text">{{ data.payment_status ? '已付' : '需付' }}</text>
					<uv-text mode='price' type='error' size="35rpx" :bold="true" :text="data.amount_real" />
				</view>
			</view>
		</view>

		<view class="ta-card" v-if="data.payments.length > 0">
			<view class="ta-card-head">支付信息</view>
			<view class="ta-card-body">
				<view v-for="p in data.payments" :key="p.code" class="tn-mb-xs ta-desc-text tn-white_bg">
					<view>支付方式：{{ p.channel_type_name }}</view>
					<view>支付单号：{{ p.code }}</view>
					<view class="flex-x">
						<view class="tn-pr-xs flex-x flex-align-center">
							<text>支付金额：</text>
							<uv-text mode="price" :text="p.payment_amount" />
						</view>
						<view v-if="p.channel_type === 'voucher'">
							<uv-tags v-if="p.audit_status === 0" size="mini" shape="circle" type="error" text="已拒绝" />
							<uv-tags v-if="p.audit_status === 1" size="mini" shape="circle" type="info" text="待审核" />
							<uv-tags v-if="p.audit_status === 2" size="mini" shape="circle" type="success" text="已完成" />
						</view>
						<view v-else>
							<uv-tags v-if="p.payment_status === 0" size="mini" shape="circle" type="info" text="未完成" />
							<template v-if="p.payment_status === 1">
								<uv-tags v-if="p.refund_status && p.audit_status === 1" size="mini" shape="circle"
									type="warning">{{ p.payment_amount > p.refund_amount ? '部分退回' : '全部退回' }}</uv-tags>
								<uv-tags v-else size="mini" shape="circle" type="success" text="已完成" />
							</template>
						</view>
					</view>
					<view>创建时间：{{ p.create_time }}</view>
				</view>
			</view>
		</view>

		<view class="ta-card" v-if="data.status == 2">

			<view class="ta-card-head flex-center">
				<view class="tn-mt-xs" v-if="data.payment_amount > 0">已支付 {{ Number(data.payment_amount) }} 元，</view>
				<view class="tn-mt-xs flex-x flex-center">
					<view class="tn-text-sm ta-desc-text">需要支付</view>
					<view>
						<uv-text mode="price" :bold="true" type="error"
							:text="Number(data.amount_real) - Number(data.payment_amount)"></uv-text>
					</view>
				</view>
			</view>


			<view class="ta-card-body">

				<uv-form style="width:500rpx;margin:0 auto">

					<view class="tn-mt" v-if="maxBalance > 0">
						<uv-input placeholder="请输入余额" v-model.number="useBalance" :max="maxBalance" type="digit"
							shape="circle" inputAlign="center" @change="setBalanceValue">
							<template v-slot:prefix><uv-text text=" 余额支付" /></template>
							<template v-slot:suffix>
								<uv-text type="info" shape="circle" size="mini" :text="`已抵扣 ${useBalance} 元`" />
							</template>
						</uv-input>
						<view class="ta-desc-text tn-text-xs tn-text-right tn-mt-xs">
							最多可使用 <text>{{ Number(maxBalance.toFixed(2)) }}</text> 元余额支付
						</view>
					</view>

					<view class="tn-mt" v-if="maxIntegral > 0">

						<uv-input placeholder="请输入积分" v-model.number="useIntegral" :max="maxIntegral" type="digit"
							shape="circle" inputAlign="center" @change="setIntegralValue">
							<template v-slot:prefix><uv-text text=" 积分抵扣" /></template>
							<template v-slot:suffix>
								<uv-text type="info" shape="circle" size="mini" :text="`已抵扣 ${useIntegral * ratio} 元`" />
							</template>
						</uv-input>

						<view class="ta-desc-text tn-text-xs tn-text-right tn-mt-xs">
							最多可使用 {{ maxIntegral.toFixed(0) }} 个积分抵扣 {{ Number((maxIntegral * ratio).toFixed(2)) }} 元
						</view>
					</view>

				</uv-form>

				<view class="flex-x tn-mt-xl" v-if="channels.length > 0 && realPayment > 0">
					<text class="tn-text-sm nowrap">在线支付：</text>
					<uv-radio-group v-model="channel" placement="column">
						<view class="tn-mb-sm flex-x" v-for="x in channels" :key="x.code">
							<uv-radio :name="x.code" size="40rpx" />
							<view class="tn-pl-xs tn-pr-sm">
								<uv-image :src="x.cover" width="45rpx" height="45rpx" />
							</view>
							<view>{{ x.name }}</view>
						</view>
					</uv-radio-group>
				</view>

				<uv-transition :show="true" mode="slide-left">
					<view class="flex-center tn-mt-lg">
						<uv-button type="success" shape="circle" @click="loadPayment"
							customStyle="width:450rpx;height:90rpx" :text="`支付 ${realPayment} 元`" />
					</view>
				</uv-transition>

				<uv-transition :show="true" mode="slide-right">
					<view class="flex-center tn-mt-lg tn-mb">
						<uv-button type="error" shape="circle" @click="cancelPayment" text="取消支付"
							customStyle="width:450rpx;height:90rpx" />
					</view>
				</uv-transition>
			</view>

			<!-- 线下凭证支付 -->
			<uv-popup ref="mpay" mode="bottom" :closeable="true" round="15rpx">
				<view class="tn-p tn-pb-sm tn-text-center">上传支付凭证，需要后台审核</view>
				<uv-line margin="0 0 15rpx 0" />
				<view class="tn-p-xs flex-center" v-if="vouchar.data.qrcode">
					<uv-image :src="vouchar.data.qrcode" width="350rpx" height="350rpx" radius="15rpx" :lazy-load="true" />
				</view>
				<view class="flex-center flex-y tn-pb-xl">
					<view class="tn-mt">
						<uv-image v-if="vouchar.image" :src="vouchar.image" width="350rpx" height="350rpx" radius="15rpx"
							:lazy-load="true" />
						<view v-else style="width:350rpx;height:350rpx" @click="chooseVoucharImage"
							class="flex-center tn-radius tn-border-r tn-gray_border">
							<uv-icon name="photo" :size="100" color="gray" />
						</view>
						<view class="tn-mt-xs tn-text-sm tn-text-center tn-gray_text">支付凭证图片</view>
					</view>
					<view class="tn-mt-xl flex-center">
						<uv-transition :show="true" mode="slide-left">
							<uv-button type="warning" shape="circle" @click="chooseVoucharImage"
								customStyle="width:450rpx;height:90rpx" :text='vouchar.image ? "重新上传" : "上传凭证"' />
						</uv-transition>
					</view>
					<view class="tn-mt flex-center">
						<uv-transition :show="true" mode="slide-right">
							<uv-button type="success" shape="circle" @click="loadPayment(true)"
								customStyle="width:450rpx;height:90rpx" text="确认提交" />
						</uv-transition>
					</view>
				</view>
			</uv-popup>

			<!-- 二维码支付 -->
			<uv-popup ref="qrcpay" mode="bottom" :closeable="true" round="15rpx">
				<view class="tn-p tn-pb-sm tn-text-center">请扫码完成支付</view>
				<uv-line margin="0 0 15rpx 0" />
				<view class="tn-p">
					<view class="tn-p-lg flex-center">
						<image style="width:400rpx" mode="widthFix" :src="qrcpay.data.qrcode"></image>
					</view>
					<view class="flex-center flex-y tn-pb flex-center">
						<view>微信支付参数</view>
						<view>
							<pre>{{ qrcpay }}</pre>
						</view>
					</view>
				</view>
			</uv-popup>

		</view>
	</view>
</template>

<script lang="ts">

import { defineComponent } from 'vue'
import { TaUseAccount, TaToast, TaImageToBase64, TaDataOrder } from '@/utils';

export default defineComponent({
	setup() {
		return TaUseAccount()
	},
	data() {
		return {
			code: <string>'', // 当前订单编号
			data: <any>{ // 当前订单对象
				payments: []
			},
			init: <boolean>false,// 是否初始化参数
			stocks: <number>0, // 订单包含商品数量
			addrid: <number>0, // 指定收货地址编号
			// 支付通道
			channel: <string>'', // 已选择支付通道
			channels: <any[]>[], // 可用的支付配置
			// 支付金额数据
			ratio: <number>0.01, // 积分抵扣比例
			maxBalance: <number>0, // 当前最大余额支付
			maxIntegral: <number>0, // 当前最大积分抵扣
			useBalance: <number>0, // 使用余额支付
			useIntegral: <number>0, // 使用积分抵扣
			usedPayment: <number>0.00, // 已经支付金额
			realPayment: <number>0.00, // 剩余支付金额
			// 凭证支付数据
			vouchar: <any>{
				data: {},
				image: '',
				qrcode: '',
			},
			// 二维码支付数据
			qrcpay: <any>{
				data: {},
				qrcode: ''
			},
		}
	},
	onLoad(options: any) {
		this.code = options.code || '-'
		this.addrid = options.addrid || 0
	},
	onShow() {
		// 加载订单数据
		this.loadChannel()
		this.loadData().then(() => this.addrid ? this.doPerfect() : '').catch(() => {
			TaToast.error("加载订单异常！").then(() => this.goto.home())
		})
		uni.stopPullDownRefresh()
	},
	// 下拉刷新订单内容
	onPullDownRefresh() {
		this.loadData();
		setTimeout(() => uni.stopPullDownRefresh(), 1000);
	},
	methods: {
		// 选择支付凭证图片
		chooseVoucharImage() {
			uni.chooseImage({
				count: 1, sourceType: ['album'], complete: (res: any) => {
					let blob = res.tempFilePaths[0]
					TaImageToBase64(blob, 500).then((img: any) => this.vouchar.image = img)
				}
			})
		},
		// 设置使用余额值
		setBalanceValue(value: any) {
			this.init || this.initValue();
			this.$nextTick(() => {
				this.useBalance = Math.max(Math.min(Number(value), this.maxBalance), 0)
				this.syncShow()
			})
		},
		// 设置使用积分值
		setIntegralValue(value: any) {
			this.init || this.initValue();
			this.$nextTick(() => {
				this.useIntegral = Math.max(Math.min(Number(value), this.maxIntegral), 0)
				this.syncShow()
			});
		},
		// 计算最大可用余额
		initValue() {
			this.init = true;
			// 减去已经使用额度
			let payBalance: number = 0, payIntegral: number = 0;
			this.ratio = Number(this.data.ratio_integral);
			this.data.payments.map((x: any) => {
				if (x.channel_type === 'balance') payBalance += Number(x.used_balance);
				if (x.channel_type === 'integral') payIntegral += Number(x.used_integral);
			});
			// 最大可用余额
			this.maxBalance = Number(Math.min(this.userinfo.extra.balance_usable, this.data.allow_balance - payBalance));
			// 最大可用积分
			this.maxIntegral = Number(Math.min(this.userinfo.extra.integral_usable, this.data.allow_integral - payIntegral));
			return this;
		},
		// 同步显示价格
		syncShow() {
			// 初始化当前变量状态
			this.init || this.initValue();
			// 当前订单剩余支付金额
			this.realPayment = Number((this.data.amount_real - this.data.payment_amount - this.useBalance - this.useIntegral * this.ratio).toFixed(2));
			return this;
		},
		// 加载订单数据
		loadData() {
			return new Promise((resolve, reject) => {
				TaDataOrder.get({ order_no: this.code }).then((ret: any) => {
					if (ret.data.list.length > 0) {
						this.stocks = 0
						this.data = ret.data.list[0]
						this.data.items.forEach((x: any) => this.stocks += x.stock_sales)
						this.syncShow() && resolve(ret)
					} else {
						reject(this.data = { payments: [] })
					}
				}).catch(reject)
			})
		},

		// 加载支付通过
		loadChannel() {
			TaDataOrder.channle({ order_no: this.code }).then((ret: any) => {
				this.channels = ret.data.channels;
				this.channels.some(x => this.channel ? false : (this.channel = x.code) !== false)
			})
		},

		// 加载支付参数
		loadPayment(force: boolean = false) {
			if (!this.channel) {
				TaToast.error('请选择支付方式')
				return
			}
			let option: any = null
			this.channels.some((x: any) => x.code == this.channel ? (option = x) !== null : false)
			// 凭证支付，需要先上传凭证图片
			if (!force && option.type === 'voucher') {
				// @ts-ignore
				this.$refs.mpay.open();
				this.vouchar.data = option
				this.vouchar.code = option.code
				return
			}
			TaDataOrder.payment({
				order_no: this.code,
				balance: this.useBalance,
				integral: this.useIntegral,
				channel_code: this.channel,
				payment_image: this.vouchar.image,
			}).then((ret: any) => {
				// 当前支付类型
				let type = ret.data.channel.type
				console.log(type,42772)
				// 凭证支付结果处理
				if (type === 'voucher') {
					return TaToast.success(ret.info).then(() => this.goto.order(this.code, true))
				}
				// 微信 H5 页面发起支付
				if (type === 'wechat_wap') {
					if (ret.data.params.h5_url) {
						return TaToast.success('正在跳转支付...').then(() => location.href = ret.data.params.h5_url);
					}
				}
				// 微信公众号及 H5 发起支付
				if (type === 'wechat_wap' || type === 'wechat_gzh') {
					return TaDataOrder.jsapi(ret.data.params).then((res: any) => {
						console.log('success:' + JSON.stringify(res))
						this.goto.order(this.code, true);
					}).catch((res: any) => {
						console.log('fail:' + JSON.stringify(res))
					})
				}
				// 微信小程序发起支付
				if (type === 'wechat_xcx') {
					return uni.requestPayment({
						provider: 'wxpay',
						...ret.data.params,
						success: (res: any) => {
							console.log('success:' + JSON.stringify(res))
							this.goto.order(this.code, true)
						},
						fail: (err: any) => {
							console.log('fail:' + JSON.stringify(err))
						}
					})
				}
				// 微信 App 发起支付
				if (type === 'wechat_app') {
					return uni.requestPayment({
						provider: 'wxpay',
						orderInfo: ret.data.params,
						success: (res: any) => {
							console.log('success:' + JSON.stringify(res))
							this.goto.order(this.code, true)
						},
						fail: (err: any) => {
							console.log('fail:' + JSON.stringify(err))
						}
					})
				}
				// 微信二维码发起支付
				if (type === 'wechat_qrc') {
					this.qrcpay.show = true
					this.qrcpay.data = ret.data.params || {}
					return true;
				}
				// 其他支付状态处理
				console.log(ret.data)
				TaToast.success(ret.info).then(() => this.goto.order(this.code, true))
			})
		},

		// 取消支付
		cancelPayment() {
			TaToast.confirm('确认要取消订单吗？').then(() => {
				TaDataOrder.cancel({ order_no: this.code }).then((ret: any) => {
					TaToast.success(ret.info).then(() => this.goto.order(this.code, true));
				})
			})
		},

		// 选择收货地址
		doSelectAddress() {
			if (this.data.delivery_type !== 1) return
			if (this.data.status !== 1 && this.data.status !== 2) return
			this.goto.addrSelect(`/pages/order/mpay?code=${this.code}`)
		},

		// 确认收货地址
		doPerfect() {
			if (this.data.delivery_type !== 1) return
			if (this.data.status !== 1 && this.data.status !== 2) return
			TaDataOrder.prefect({ order_no: this.code, address_id: this.addrid }).then(ret => {
				console.log('prefect', ret)
				this.loadData();
			}).catch((ret: any) => {
				console.log('prefect', ret)
			})
		},
	}
})
</script>